<?php
if(!isset($_SESSION)){
    session_start();
}
include_once '../tools/tools.logger.php';
include_once '../config.inc.php';
require_once '../system.UIShujuZhongxin.php';

@ $code=$_REQUEST['code'];
@ $state=$_REQUEST['state'];
$openId="";

@ $公众号Id = G_SERV_ID;

$param = '';
if (array_key_exists('param', $_GET)) {
    $param = $_GET['param'];
    $param = json_decode(urldecode($param), true);
    $param = http_build_query($param);
}


if($code){
    global $G_CONFIG;

    $公众号appId = $G_CONFIG['公众号信息'][$公众号Id]['公众号AppId'];
    $secret= $G_CONFIG['公众号信息'][$公众号Id]['公众号AppSecret'];

    logger()->logDebug("wxtunnel, :".$公众号Id.$公众号appId.$secret.'code is  '.$code.' end.');

    $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$公众号appId}&secret={$secret}&code={$code}&grant_type=authorization_code";
    $ret=curl_get_contents($url);
    $obj=json_decode($ret);

    logger()->logDebug("wxtunnel return, :".$ret.' end.');
    if ($obj) {
        $openId= $obj->openid;

        $_SESSION['vo用户数据']['openID'] = $openId;
        $bm=new CUI数据中心(Page::y用户中心,$openId);
        $bm->fg给session赋值();


    }
    else
        echo 'OpenId get failed!';

}else{
      echo 'Oauth failed';
}

logger()->logDebug("wxtunnel, code:[$code];state:[$state];openId:[$openId]");

$url = "index.php?state={$state}";
if ($param) $url = $url . "&". $param;
header("Location: " . $url);
exit(0);


function curl_get_contents($url,$timeout=3) {
    $curlHandle = curl_init();
    curl_setopt( $curlHandle , CURLOPT_URL, $url );
    curl_setopt( $curlHandle , CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $curlHandle , CURLOPT_TIMEOUT, $timeout );
    $result = curl_exec( $curlHandle );
    curl_close( $curlHandle );
    return $result;
}
